import store from '@/store';
import config from '@/common/config';

export default {
  request(options = {}) {
    const {baseUrl, data = {}, url, method} = options;
    const _config = {
      baseUrl: baseUrl || config.baseUrl,
      data: data || {},
      url: (baseUrl || config.requestUrl) + url,
      method: method || 'POST',
      header: {
        'Content-Type':
          options.contentType == 'json'
            ? 'application/json'
            : 'application/x-www-form-urlencoded;charset=UTF-8',
      },
    };

    const token = store.getters.token;
    const openId = store.getters.openId;
    if (token) {
      _config.data.token = token;
    }
    if (openId) {
      _config.data.openId = openId;
    }
    let timeoutId = null;
    if (!options.hideLoading) {
      timeoutId = setTimeout(() => {
        uni.showLoading({
          icon: 'none',
          title: options.loadingTitle || '加载中',
        });
      }, 200);
    }

    return new Promise((resolve, reject) => {
      uni.request({
        ..._config,
        success(res) {
          const response = res.data;
          if (res.statusCode === 200) {
            //成功
            const code = response.code;
            // 返回数据格式化 100200：成功
            if (code === 100200) {
              if (!response.data) {
                // console.log('responseData:', response.data);
              }
              if (options.responseData) {
                resolve(response);
              } else {
                resolve(response.data);
              }
            } else {
              uni.showToast({icon: 'none', title: response.msg || '网络异常'});
            }
          } else {
            uni.showToast({icon: 'none', title: '网络异常'});
            reject(res);
          }
        },
        fail(err) {
          reject(err);
          uni.showToast({icon: 'none', title: '网络异常'});
        },
        complete() {
          if (!options.hideLoading) {
            uni.hideLoading();
          }
          clearTimeout(timeoutId);
        },
      });
    });
  },
  get(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = 'GET';
    return this.request(options);
  },
  post(url, data, options = {}) {
    const option = {
      url,
      data,
      method: 'POST',
      ...options,
    };
    return this.request(option);
  },
  delete(url, data, options = {}) {
    const option = {
      url,
      data,
      method: 'DELETE',
      ...options,
    };
    return this.request(option);
  },
  upload(url, options = {}) {
    return new Promise((resolve, reject) => {
      const {filePath, name = 'CardImage'} = options;
      const customerId = store.getters.customerId;
      uni.uploadFile({
        url: config.requestUrl + url,
        filePath,
        name,
        header: {
          'Content-Type': 'multipart/form-data',
        },
        formData: {
          customerId,
        },
        success: function (res) {
          const data = JSON.parse(res.data);
          resolve(data.data);
        },
        fail: function (err) {
          reject(err);
          console.log(err);
        },
        complete: function () {
          // uni.hideLoading();
        },
      });
    });
  },

  // 选择图片
  uploadImage(obj) {
    return new Promise((resove) => {
      const _this = this;
      uni.chooseImage({
        count: obj.count || 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          const tempFilePaths = res.tempFilePaths;
          _this.uploadRequest(tempFilePaths, 0, tempFilePaths.length, (result) => {
            _this.imgUrlList = [];
            resove(result);
          });
        },
      });
    });
  },

  // 图片上传
  uploadRequest(tempFilePath, count, length, callback) {
    const _this = this;
    const title = length == 1 ? '上传中...' : `正在上传第${count}张`;
    uni.showLoading({
      title,
    });
    uni.uploadFile({
      url: config.uploadUrl,
      filePath: tempFilePath[count],
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data',
      },
      formData: {},
      success(res) {
        console.log(res);
        if (res.statusCode !== 200) {
          _this.$dialog.toast('上传失败');
        } else {
          const data = JSON.parse(res.data);
          if (data.code == '100200') {
            if (!data.data.url) {
              _this.$dialog.toast('上传失败，服务器异常');
            } else {
              _this.imgUrlList.push(data.data.url + data.data.pathUrl);
            }
          }
        }
      },
      fail(err) {
        console.log(err);
      },
      complete() {
        count++;
        if (count == length) {
          _this.$dialog.toast('上传完成');
          uni.hideLoading();
          if (typeof callback == 'function') {
            callback(_this.imgUrlList);
          }
        } else {
          // 递归调用下一张图片上传
          _this.uploadRequest(tempFilePath, count, length, callback);
        }
      },
    });
  },
};
